package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseFragment;
import com.gongpingjialoan.activity.tool.WebViewActivity;
import com.gongpingjialoan.adapter.NewCarLooperAdapter;
import com.gongpingjialoan.adapter.NewCarSourceListAdapter;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.data.CategoryData;
import com.gongpingjialoan.data.NewCarActivityData;
import com.gongpingjialoan.data.NewCarBrand;
import com.gongpingjialoan.data.NewCarList;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.view.NewCarSortLinearLayout;
import com.gongpingjialoan.widget.autoviewpagers.ColorPointHintView;
import com.gongpingjialoan.widget.autoviewpagers.RollPagerView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import scrollable.CanScrollVerticallyDelegate;
import scrollable.OnFlingOverListener;
import scrollable.OnScrollChangedListener;
import scrollable.ScrollableLayout;

import static android.content.Context.MODE_PRIVATE;
import static com.alibaba.sdk.android.feedback.impl.FeedbackAPI.mContext;

/***
 * 新车界面
 *
 * @author hcg
 */
public class NewCarFragment extends BaseFragment implements OnClickListener, AbsListView.OnItemClickListener, NetDataJson.OnStringListener,
        OnRefreshListener<ListView>, OnLastItemVisibleListener, NewCarSortLinearLayout.GeCarList {

    public CategoryData mCategoryData;

    private View mainV;

    private PullToRefreshListView pullToRefreshListView;

    private ListView listView;

    private NewCarSourceListAdapter carSourceAdapter;

    private boolean isLoadingMore;

    private boolean hasMore, isSuggest;

    private List<NewCarList.ResultsBean> mResultsBean;

    private NetDataJson netWork;

    private boolean isRefresh = true;

    private NewCarSortLinearLayout mSortLinearLayout;

    private ImageView nocarImageView;

    public String fromType = "";

    private View footView;

    private View loading;

    private View suggestHeadView, tabview, headerView;

    private ScrollableLayout mScrollableLayout;
    private ImageView recommd_img1;
    private ImageView recommd_img2;
    private LinearLayout rollLinearLayout;
    private RollPagerView mRollPagerView;
    private String brand_slug;
    private String campaign_id;
    private NetDataJson getCarBrandsnetDataJson;
    private String mPriceSort;
    private NetDataJson getNewCarActivityDetail;
    public NewCarActivityData newCarActivityData;
    private NewCarLooperAdapter mLooperAdapter;
    private String nextUrl;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mCategoryData = GPJApplication.getInstance().getCategoryData();
        mainV = inflater.inflate(R.layout.newcarlist_fragment, null);
        footView = inflater.inflate(R.layout.listview_footview, null);
        suggestHeadView = inflater.inflate(R.layout.suggest_head, null);
        suggestHeadView.setOnClickListener(this);
        netWork = new NetDataJson(this, 1);
        rollLinearLayout = (LinearLayout) mainV.findViewById(R.id.rollmain);

        initView();
        initData();
        return mainV;
    }


    public void initData() {
        campaign_id = getActivity().getSharedPreferences("NEW_CAR_ACTIVITY", MODE_PRIVATE).getString("campaign_id", "");
        getCarBrands(false);
        getNewCarActivityDetail();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            stopPlay();
        } else {
            startPlay();
            initData();
        }
    }

    public void stopPlay() {
        if (mRollPagerView != null) {
            mRollPagerView.stopPlay();
        }


    }

    public void startPlay() {
        if (mRollPagerView != null) {
            mRollPagerView.startPlay();
        }
    }

    private void initView() {
        mScrollableLayout = (ScrollableLayout) mainV.findViewById(R.id.scrollable_layout);
        tabview = mainV.findViewById(R.id.tabs);
        headerView = mainV.findViewById(R.id.header);
        mScrollableLayout.setDraggableView(tabview);
        mScrollableLayout.setOnScrollChangedListener(new OnScrollChangedListener() {
            @Override
            public void onScrollChanged(int y, int oldY, int maxY) {
                Utils.LogD("y=" + y + "oldY=" + oldY + "y=" + maxY);
                final float tabsTranslationY;
                if (y < maxY) {
                    tabsTranslationY = .0F;
                } else {
                    tabsTranslationY = y - maxY;
                }
                tabview.setTranslationY(tabsTranslationY);
                headerView.setTranslationY(y / 2);
            }
        });

        mSortLinearLayout = (NewCarSortLinearLayout) mainV.findViewById(R.id.menu_layout);
        mSortLinearLayout.setGeCarList(this);

        nocarImageView = (ImageView) mainV.findViewById(R.id.no_car_id);
        loading = mainV.findViewById(R.id.main_loading);
        recommd_img1 = (ImageView) mainV.findViewById(R.id.recommd_img1);
        recommd_img2 = (ImageView) mainV.findViewById(R.id.recommd_img2);
        recommd_img1.setOnClickListener(this);
        recommd_img2.setOnClickListener(this);

        pullToRefreshListView = (PullToRefreshListView) mainV.findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);
        mResultsBean = new ArrayList<>();

        isLoadingMore = true;
        hasMore = true;

        carSourceAdapter = new NewCarSourceListAdapter(getActivity());
        listView = pullToRefreshListView.getRefreshableView();
        listView.addHeaderView(suggestHeadView);
        listView.addFooterView(footView);
        listView.setAdapter(carSourceAdapter);
        listView.setOnItemClickListener(this);
        listView.removeHeaderView(suggestHeadView);
        listView.removeFooterView(footView);
        carSourceAdapter.notifyDataSetChanged();

        mScrollableLayout.setCanScrollVerticallyDelegate(new CanScrollVerticallyDelegate() {
            @Override
            public boolean canScrollVertically(int direction) {
                return listView != null && listView.canScrollVertically(direction);
            }
        });
        mScrollableLayout.setOnFlingOverListener(new OnFlingOverListener() {
            @Override
            public void onFlingOver(int y, long duration) {
                if (listView != null) {
                    listView.smoothScrollBy(y, (int) duration);
                }
            }
        });
    }


    @Override
    public void onDestroy() {
        if (netWork != null) {
            netWork.cancelTask();
        }
        if (getCarBrandsnetDataJson != null) {
            getCarBrandsnetDataJson.cancelTask();
        }
        if (getNewCarActivityDetail != null) {
            getNewCarActivityDetail.cancelTask();
        }
        super.onDestroy();
    }


    @Override
    public void onClick(View v) {
        if (v == recommd_img1) {
            gotoWeb(0);
        } else if (v == recommd_img2) {
            gotoWeb(1);
        }
    }

    private void gotoWeb(int position) {
        if (newCarActivityData != null && newCarActivityData.getRecommendations() != null && newCarActivityData.getRecommendations().size() > position) {
            String url = newCarActivityData.getRecommendations().get(position).getUrl();
            if(TextUtils.isEmpty(url))return;
            Intent intent = new Intent(getActivity(), WebViewActivity.class);
            intent.putExtra("url", url);
            intent.putExtra("content", "webViewTitle");
            getActivity().startActivity(intent);
        }
    }


    public void updateListView() {
        if (mResultsBean.size() != 0) {
            carSourceAdapter.setData(mResultsBean);
            pullToRefreshListView.onRefreshComplete();
            nocarImageView.setVisibility(View.GONE);
            isLoadingMore = false;
        } else {
            nocarImageView.setVisibility(View.VISIBLE);
        }
    }


    public void refresh() {
        if (pullToRefreshListView != null) {
            pullToRefreshListView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    pullToRefreshListView.setRefreshing();
                }
            }, 300);
        }
    }

    // 重新获取数据
    private void onUpdateData() {
        if (pullToRefreshListView.isRefreshing())
            loading.setVisibility(View.GONE);
        isRefresh = true;
        nocarImageView.setVisibility(View.GONE);
        hasMore = true;
        updateData("");

    }


    private void updateData(String nextUrl) {
        netWork.clearMap();
        if(TextUtils.isEmpty(nextUrl)){
            netWork.setUrl(NetDataJson.NEWCAR_SERVER_DOMAIN + "/api/v2/tesla/campaigns/" + campaign_id + "/cars/");
            netWork.addParam("brand_slug", brand_slug);
            if (!TextUtils.isEmpty(mPriceSort)) {
                netWork.addParam("sort", mPriceSort);
            }
        }else{
            netWork.setUrl(nextUrl);
        }
        netWork.addDeviceCode = false;
        netWork.setUseOtherDomain(true);
        netWork.request("get");

    }


    // 加载更多
    private void LoadMoreData() {
        if (!hasMore) {
            Toast.makeText(getActivity(), "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isLoadingMore && hasMore && mResultsBean.size() > 0) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            isLoadingMore = true;
            updateData(nextUrl);
        }
    }


    @Override
    public void onDataJsonError(String errorMessage) {
        Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
        loading.setVisibility(View.GONE);
        if (isLoadingMore && !isRefresh) {
            listView.removeFooterView(footView);
        }
        isLoadingMore = false;
        hasMore = false;
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onDataJsonUpdate(String json) {
        loading.setVisibility(View.GONE);
        if (isLoadingMore && !isRefresh) {
            listView.removeFooterView(footView);
        }
        if (isRefresh) {
            mResultsBean.clear();
            listView.removeHeaderView(suggestHeadView);
            carSourceAdapter.notifyDataSetChanged();
        }
        Gson gson = new Gson();
        NewCarList newCarList = gson.fromJson(json, NewCarList.class);

        mResultsBean.addAll(newCarList.getResults());
        if (mResultsBean == null || mResultsBean.size() == 0) {
            Toast.makeText(getActivity(), "未找到相应数据", Toast.LENGTH_SHORT).show();
            nocarImageView.setVisibility(View.VISIBLE);
            isLoadingMore = false;
            pullToRefreshListView.onRefreshComplete();
            isSuggest = false;
            return;
        }
        isSuggest = false;

        nextUrl = newCarList.getNext();
        if (TextUtils.isEmpty(nextUrl)) {
            hasMore = false;
        }
        updateListView();
    }


    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

        NewCarList.ResultsBean data = mResultsBean.get(position - listView.getHeaderViewsCount());
        Intent it = new Intent(getActivity(), NewCarDetailActivity.class);
        it.putExtra("carid", data.getId() + "");
        startActivity(it);
    }


    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        StepMonitor.getInstance().addMonitor(new Monitor("scroll", action, System.currentTimeMillis(), roll_pages));
        reset();
        String label =
                "更新时间:" + DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                        | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
        refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        getCarBrands(true);
    }

    @Override
    public void onLastItemVisible() {
        LoadMoreData();
    }


    @Override
    public void getCarList(String priceSort, String brand_slug) {
        this.brand_slug = brand_slug;
        mPriceSort = priceSort;
        pullToRefreshListView.setRefreshing();
    }


    /**
     * 获取新车品牌
     */
    private void getCarBrands(final boolean isRefresh) {
        getCarBrandsnetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
            }

            @Override
            public void onDataJsonUpdate(String json) {
                ArrayList<NewCarBrand> newCarBrandList = new ArrayList<>();
                try {
                    JSONArray jsonArray = new JSONArray(json);
                    int size = jsonArray.length();

                    for (int i = 0; i < size; i++) {
                        JSONObject j = (JSONObject) jsonArray.get(i);
                        NewCarBrand newCarBrand = new NewCarBrand();
                        newCarBrand.setBrand(j.getString("brand"));
                        newCarBrand.setBrand_slug(j.getString("brand_slug"));
                        newCarBrandList.add(newCarBrand);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(!isRefresh){
                    brand_slug = "";
                }

                NewCarBrand newCarBrand = new NewCarBrand();
                newCarBrand.setBrand("全部品牌");
                newCarBrand.setBrand_slug("");
                newCarBrandList.add(0,newCarBrand);
                mSortLinearLayout.setBrands(newCarBrandList);
                onUpdateData();
            }
        }, 1);

        getCarBrandsnetDataJson.setUrl(NetDataJson.NEWCAR_SERVER_DOMAIN + "/api/v2/tesla/campaigns/" + campaign_id + "/cars/brands/");
        getCarBrandsnetDataJson.setUseOtherDomain(true);
        getCarBrandsnetDataJson.request("get");
    }

    /**
     * 获取新车活动详情
     */
    private void getNewCarActivityDetail() {
        getNewCarActivityDetail = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
            }

            @Override
            public void onDataJsonUpdate(String json) {
                Gson gson = new Gson();
                newCarActivityData = gson.fromJson(json, NewCarActivityData.class);
                List<NewCarActivityData.BannersBean> banners = newCarActivityData.getBanners();

                if (banners != null && banners.size() > 0) {
                    rollLinearLayout.removeAllViews();
                    mRollPagerView = new RollPagerView(getActivity());
                    mRollPagerView.setHintView(new ColorPointHintView(getActivity(), Color.WHITE, Color.GRAY));
                    mRollPagerView.setPlayDelay(2000);
                    rollLinearLayout.addView(mRollPagerView);
                    mRollPagerView.setVisibility(View.VISIBLE);
                    mLooperAdapter = new NewCarLooperAdapter(mRollPagerView, banners, getActivity(), getFragmentManager());
                    mRollPagerView.setAdapter(mLooperAdapter);
                }
                if (newCarActivityData != null && newCarActivityData.getRecommendations() != null && newCarActivityData.getRecommendations().size() >= 2) {
                    Glide.with(mContext).load(newCarActivityData.getRecommendations().get(0).getImage_url()).placeholder(R.drawable.trans).error(R.drawable.trans).into(recommd_img1);
                    Glide.with(mContext).load(newCarActivityData.getRecommendations().get(1).getImage_url()).placeholder(R.drawable.trans).error(R.drawable.trans).into(recommd_img2);
                }

            }
        }, 1);

        getNewCarActivityDetail.setUrl(NetDataJson.NEWCAR_SERVER_DOMAIN + "/api/v2/tesla/campaigns/" + campaign_id + "/");
        getNewCarActivityDetail.setUseOtherDomain(true);
        getNewCarActivityDetail.request("get");
    }

}
